package com.ruoyi.datastatistics.Agreement;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.basedata.domain.TerminalsXb;
import com.ruoyi.basedata.domain.vo.ConcentratorCommand;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.datastatistics.vo.CommandGenerator;
import org.apache.commons.lang3.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class SiLianV1 {

    private static final Map<Integer, CommandGenerator> commandGenerators = new HashMap<>();

    // 00H 确认∕否认
    //01H 复位
    //02H 链路接口检测
    //03H 设置参数
    //04H 控制命令
    //05H~09H 备用
    //0AH 查询参数
    //0BH 请求 1 类数据（实时数据）
    // 0CH 请求 2 类数据（历史数据）
    // 0DH 数据转发（如通过管理中心对表进行直接通讯）
    // 0EH~FFH 备用
    public static byte[] AFN = { 0x00,0x01,0x02,0x03,0x04,0x0a,0x0b,0x0c,0x0d };
    public static byte[][] Fn = {
            {0x01,0x02,0x03,0x04},
            {0x01,0x02,0x03,0x04},
            {0x01,0x02,0x03,0x04,0x06,0x16},
            {0x01,0x02,0x03,0x04,0x06,0x16},
            {0x01,0x02,0x03,0x04,0x05,0x06},
            {0x01,0x02,0x03,0x04,0x06,0x07,0x08},
            {0x01,0x02,0x4,0x6},
            {0x01,0x02}
    };

    public static void main(String[] args) {
//        getpacketLength(331);
    }

    /**
     * 实时数据 全抄
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForMeterReadingAll(String concentratorAddress){
        byte[] bit = new byte[8];
        bit[0] = 0x10;
        byte[] temp = new byte[6];
        temp = new byte[]{(byte)0xFF,(byte)0xFF,0x00,0x00,(byte)0xFF,(byte)0xFF};
        System.arraycopy(temp, 0, bit, 1, temp.length);
        bit[7] = 0x45;
        return getpacketbody(concentratorAddress,6,2,bit,1);
    }

    /**
     * 批量下载表档案
     * @param concentratorAddress
     * @param meterArray
     * @param collectorArray
     * @return
     */
    public static byte[] getCommandDataForBoundMeter(String[] meterArray,String[] collectorArray,String concentratorAddress){
        byte[] bit = new byte[2+16*meterArray.length];
        bit[0] = (byte) 0x01;
        bit[1] = (byte) meterArray.length;
        for (int i = 0; i < meterArray.length; i++) {
            System.out.println(meterArray[i]+"-"+collectorArray[i]);
            byte[] terminal = new byte[16];
            terminal[0] = (byte) 0x10;//表类型
            terminal[1] = (byte) 0x01;//数据纠错标志
            terminal[2] = (byte) 0x00;//计量表序号
            byte[] bit1 = CharacterParsingCommon.get16tobcd(meterArray[i], false);
            for (int j = 0; j < bit1.length; j++) {
                terminal[3 + j] = bit1[j];
            }
            byte[] bit2 = CharacterParsingCommon.get16tobcd(collectorArray[i], false);
            for (int l = 0; l < bit2.length; l++) { //采集器通讯地址
                terminal[9 + l] = bit2[l];
            }
            terminal[15] = (byte) 0x45;//数据项
            System.arraycopy(terminal,0,bit,2+(i*16),16);
        }
        return getpacketbody(concentratorAddress,3,5,bit,0);
    }

    /**
     * 实时数据  抄一个
     * @param concentratorAddress
     * @param meterAddress
     * @return
     */
    public static byte[] getCommandDataForMeterReadingOne(String concentratorAddress,String meterAddress){
        byte[] bit = new byte[8];
        bit[0] = 0x10;
        byte[] temp = new byte[6];
        temp = new byte[]{(byte)0xFF,(byte)0xFF,0x00,0x00,(byte)0xFF,(byte)0xFF};
        temp = "".equals(meterAddress)? temp : CharacterParsingCommon.get16tobcd(meterAddress,false);
        System.arraycopy(temp, 0, bit, 1, temp.length);
        bit[7] = 0x45;
        return getpacketbody(concentratorAddress,6,2,bit,1);
    }

    /**
     * 开阀或者关阀
     * @param concentratorAddress
     * @param meterAddress
     * @return
     */
    public static byte[] getValveControlData(String concentratorAddress,String meterAddress,String isOpen){
        byte[] bit = new byte[7];
        bit[0] = (byte) 0x10;
        byte[] command = CharacterParsingCommon.get16tobcd(meterAddress, false);
        for (int i = 0; i < command.length; i++) {
            bit[1 + i] = command[i];
        }
        if ("0".equals(isOpen)) {
            return getpacketbody(concentratorAddress,4,1,bit,0);
        }else {
            return getpacketbody(concentratorAddress,4,2,bit,0);
        }
    }

    /**
     * 设置月冻结时间 bcd码表示 15位代表分 16位代表时 17位代表日
     * @param sendTime
     * @param frequency
     * @param concentratorAddress
     */
    public static byte[] getCommandDataForFrequencyControl(String sendTime,Integer frequency,String concentratorAddress){
        byte[] bit = new byte[3];
        String[] day = getTime(sendTime,"0302");
        for (int i = 0; i < day.length; i++) {
            bit[i] = (byte) Integer.parseInt(day[i],16);
        }
        return getpacketbody(concentratorAddress,3,3,bit,0);
    }

    /**
     * 设置ip和端口
     * @param ip
     * @param port
     * @param concentratorAddress
     */
    public static byte[] getCommandDataForIpPortControl(String ip ,String port,String concentratorAddress){
        byte[] bit = new byte[6];
        String[] split = StringUtils.split(ip,".");
        for (int i = 0; i < split.length; i++) {
            bit[i] = (byte) Integer.parseInt(Long.toHexString(Long.parseLong(split[i])),16);
        }
        byte[] pid = getPort(Integer.parseInt(port));
        bit[4] = pid[0];
        bit[5] = pid[1];
        return getpacketbody(concentratorAddress,3,1,bit,0);
    }


    /**
     * 查询集中器地址
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForConcentratorAddress(String concentratorAddress){
        return getpacketbody(concentratorAddress,5,2,null,1);
    }

    /**
     * 查询集中器抄表日
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForConcentratorReadingDay(String concentratorAddress) {
        return getpacketbody(concentratorAddress, 5, 3, null,1);
    }

    /**
     * 读取表地址
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForMeterAddress(String concentratorAddress){
        byte[] bit = new byte[7];
        bit[0] = (byte) 0x10;
        bit[1] = (byte) 0xFF;
        bit[2] = (byte) 0xFF;
        bit[3] = (byte) 0x00;
        bit[4] = (byte) 0x00;
        bit[5] = (byte) 0xFF;
        bit[6] = (byte) 0xFF;
        return getpacketbody(concentratorAddress,5,4,bit,1);
    }

    /**
     * 查询集中器当前时钟
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForConcentratorDate(String concentratorAddress){
        return getpacketbody(concentratorAddress,6,1,null,1);
    }

    /**
     * 查询集中器ip和端口
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForConcentratorIpPort(String concentratorAddress){
        return getpacketbody(concentratorAddress,5,1,null,1);
    }

    /**
     * 设置集中器地址 15.16位代表行政划码 ，17.18位代表终端地址
     * @param concentratorAddress
     * @param newAddress
     * @return
     */
    public static byte[] getCommandDataForSetConcentratorAddress(String concentratorAddress,String newAddress){
        byte[] bit = new byte[6];
        byte[] addressFieldPacket = getAddressFieldPacket(newAddress);
        for (int i = 0; i < addressFieldPacket.length ; i++) {
            bit[i] = (byte) addressFieldPacket[i];
        }
        return getpacketbody(concentratorAddress,3,2,bit,0);
    }


    /**
     * 下载表档案(一个)
     * @param concentratorAddress
     * @param meter
     * @param collector
     * @return
     */
    public static byte[] getCommandDataForDownMeterOne(String concentratorAddress,String meter,String collector){
        byte[] bit = new byte[17];
        bit[0] = (byte) 0x10;//表类型及厂商代码
        bit[1] = (byte) 0x01;//数据纠错标识
        bit[2] = (byte) 0x00;//计量表序号
        byte[] bit1 = CharacterParsingCommon.get16tobcd(meter, false);
        for (int i = 0; i < bit1.length; i++) {//计量表通讯地址
            bit[3 + i] = bit1[i];
        }
        byte[] bit2 = new byte[6];
        bit2 = CharacterParsingCommon.get16tobcd(collector, false);
        for (int i = 0; i < bit2.length; i++) { //采集器通讯地址
            bit[9 + i] = bit2[i];
        }
        bit[15] = (byte) 0x01; //运行标识
        bit[16] = (byte) 0x45; //数据项
        return getpacketbody(concentratorAddress,3,4,bit,0);
    }

    /**
     * 集中器校时
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForSetConcentratorDate(String concentratorAddress){
        byte[] bit = new byte[5];
        String[] time = getTime(new Date().toString(),"0401");
        for (int i=0;i<time.length;i++){
            bit[i] = (byte) Integer.parseInt(time[i],16);
        }
        return getpacketbody(concentratorAddress,4,0,bit,0);
    }

    /**
     * 集中器初始化
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForConcentratorInitialize(String concentratorAddress){
        return getpacketbody(concentratorAddress,1,1,null,0);
    }

    /**
     * 集中器格式化
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForConcentratorFormat(String concentratorAddress){
        return getpacketbody(concentratorAddress,1,2,null,0);
    }

    /**
     * 恢复出厂设置
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForConcentratorFactoryReset(String concentratorAddress){
        return getpacketbody(concentratorAddress,1,3,null,0);
    }

    /**
     * 集中器重启
     * @param concentratorAddress
     * @return
     */
    public static byte[] getCommandDataForConcentratorReboot(String concentratorAddress){
        return getpacketbody(concentratorAddress,1,0,null,0);
    }

    /**
     * 解析命令返回数据
     * @param bit
     * @param commandType
     * @return
     */
    public static JSONObject GetResult(byte[] bit,Integer commandType){
        JSONObject jo = new JSONObject();
        if (getCsForAllType(bit,8 ,null)){
            try {
                byte[] bytes = Arrays.copyOfRange(bit, 15, bit.length - 2);
                switch (commandType){
                    case 1:
                        getDSDateinfoFromByte(bit,123,jo);
                        break;
                    case 4:
                        getMeterStatus(bytes,jo);
                        break;
                    case 8:
                        getAdress(bytes,jo);
                        break;
                    case 9:
                        getMeterReadingDay(bytes,jo);
                        break;
                    case 10:
                        getOperatingParameters(bytes,jo);
                        break;
                    case 11:
                        getConcentratorTime(bytes,jo);
                        break;
                    case 12:
                        getConcentratorIpPort(bytes,jo);
                        break;
                    default:
                        jo.put("code","1");
                        jo.put("msg","成功");
                        break;
                }
            }catch (Exception e){
                System.out.println(e.getMessage()+"——"+"解析命令时出错");
            }
        }else {
            jo.put("code","0");
            jo.put("msg","失败");
        }
        return jo;
    }

    /**
     * 开关阀返回命令解析  TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO
     * @param bytes
     * @param jo
     */
    public static void getMeterStatus(byte[] bytes, JSONObject jo) {
        String s = CharacterParsingCommon.get16tobcd(bytes, false);
        System.out.println(s);
        jo.put("code","1");
        jo.put("msg","成功");
    }


    /**
     * 解析集中器IP和Port
     * @param bit
     * @return
     */
    public static void getConcentratorIpPort(byte[] bit,JSONObject jo) {
        String ip = hexToIp(CharacterParsingCommon.get16tobcd(Arrays.copyOfRange(bit,0,4), false));
        System.out.println(ip);
        int port = hexToPort(CharacterParsingCommon.get16tobcd(Arrays.copyOfRange(bit,4,6), true));
        System.out.println(port);
        jo.put("code","1");
        jo.put("msg","成功");
        jo.put("data","IP 地址：" + ip + ", 端口号：" + port);
    }

    /**
     * 查询集中器日期解析
     * @param bit
     * @return
     */
    public static void getConcentratorTime(byte[] bit,JSONObject jo) {
        String s = CharacterParsingCommon.get16tobcd(bit, false);
        String date = s.substring(8,10)+"年"+s.substring(6,8)+"月"+s.substring(4,6)+"日"+s.substring(2,4)+"时"+s.substring(0,2)+"分";
        jo.put("code","1");
        jo.put("msg","成功");
        jo.put("data","集中器日期："+date);
    }

    /**
     * 解析读取表地址
     * @param bit
     * @param jo
     */
    public static void getOperatingParameters(byte[] bit,JSONObject jo){

        StringBuilder stringBuilder = new StringBuilder();
        int count = 0;
        if (bit.length == 0){
            jo.put("code","1");
            jo.put("msg","成功");
            jo.put("data","    无数据");
        }else {
            byte[] bytes = Arrays.copyOfRange(bit, 6, bit.length);
            String s = CharacterParsingCommon.get16tobcd(bytes, false);
            int a = s.length()/32;
            System.out.println(a);
            for (int i = 0; i < a; i++) {
                String meter = convertCustomFormat(s.substring(4+(i*32), 16+(i*32)));
                System.out.println(meter);
                if (!"000000000000".equals(meter)){
                    count+=1;
                    stringBuilder.append(meter+"     ");
                }
            }
//            stringBuilder.deleteCharAt(stringBuilder.length()-1);
            System.out.println(stringBuilder);
            jo.put("code","1");
            jo.put("data",stringBuilder);
        }

    }

    /**
     * 查询抄表日解析
     * @param bit
     * @return
     */
    public static void getMeterReadingDay(byte[] bit,JSONObject jo) {
        String s = CharacterParsingCommon.get16tobcd(bit, false);
        String time = s.substring(4,6)+"日"+s.substring(2,4)+"时"+s.substring(0,2)+"分";
        jo.put("code","1");
        jo.put("msg","成功");
        jo.put("data","抄表日："+time);
    }

    /**
     * 查询集中器地址解析
     * @param bit
     * @return
     */
    public static void getAdress(byte[] bit,JSONObject jo){
        String s = CharacterParsingCommon.get16tobcd(bit, false);
        String address = s.substring(2,4)+s.substring(0,2)+"00"+s.substring(4,8);
        jo.put("code","1");
        jo.put("msg","成功");
        jo.put("data","集中器地址："+address);
    }

    /**
     * 计算帧校验和
     * @param commandData
     * @return
     */
    public static byte frameChecksums(byte[] commandData){
        byte[] bytes = Arrays.copyOfRange(commandData, 6, commandData.length - 2);
        int sum = 0;
        for (byte aByte : bytes) {
            sum += aByte & 0xFF;
        }
        return (byte) sum;
    }

    /**
     * 字节总数---控制域、地址域、链路用户数据（应
     * 用层）的字节总数
     * @return
     */
    public static byte[] getpacketLength(int num){
        String binaryString = Integer.toBinaryString(num);
        binaryString = binaryString+"11" ;
        int length = Integer.parseInt(binaryString, 2);
        String l_str =  Integer.toHexString(length);
        int l = l_str.length();
        for(int i=0;i<4-l;i++){
            l_str = "0" + l_str;
        }
        byte[] b = new byte[2];
        b[0] =(byte) Integer.parseInt(l_str.substring(2,4),16);
        b[1] =(byte) Integer.parseInt(l_str.substring(0,2),16);
        return b;

    }


    /**
     * 字节总数---控制域、地址域、链路用户数据（应
     * 用层）的字节总数
     * @return
     */
    public static int getpacketLength(byte[] bit){
        String hexString = "";
        for (byte b : bit) {
            hexString = String.format("%02X", b) + hexString;
        }
        int intValue = Integer.parseInt(hexString, 16);
        String binaryString = Integer.toBinaryString(intValue);
        binaryString = binaryString.substring(0,binaryString.length()-2);

        intValue = Integer.parseInt(binaryString, 2);

        return intValue;
    }


    /**
     * 地址域
     * @param address 行政码+设备地址，例如行政0923设备地址0015补充零
     * @return 2309150000 bcd码，前高后低
     */
    public static byte[] getAddressFieldPacket(String address){
        int length = address.length()/2;
        byte[] bit = new byte[5];
        byte[] temp;
        temp = CharacterParsingCommon.get16tobcd(address.substring(0,4),false);
        System.arraycopy(temp, 0, bit, 0, 2);
        temp = new byte[2];
        temp = new byte[]{(byte)0xFF, (byte)0xFF, 0x00};
        temp = address.length()<5? temp : CharacterParsingCommon.get16tobcd(address.substring(4,8),false);
        System.arraycopy(temp, 0, bit, 2, temp.length);
        bit[4] = 0x00;
        return bit;
    }

    /**
     * 地址域
     * @param bit 行政码+设备地址，例如行政0923设备地址0015补充零
     * @return 2309150000 bcd码，前高后低
     */
    public static String getAddressFieldPacket(byte[] bit){
        String address = "";
        byte[] temp = new byte[2];
        System.arraycopy(bit, 0, temp, 0, 2);
        address = CharacterParsingCommon.get16tobcd(temp,true);

        temp = new byte[2];
        System.arraycopy(bit, 2, temp, 0, 2);
        address = address + CharacterParsingCommon.get16tobcd(temp,true);
        address = address +"00";
        return address;
    }

    /**
     * 控制码
     * @param type
     * @return
     */
    public static byte getControlPacket(int type){
        return type==1? (byte)0x4b : 0x4a;
    }

    /**
     * SEQ
     * @param fir 报文的第一帧
     * @param fin 报文的最后一帧
     * @param con 请求确认标志位 CON
     * @return
     */
    public static byte getSEQPacket(int fir,int fin,int con){
        String str = String.valueOf(fir)  + String.valueOf(fin) + String.valueOf(con)+ "0000";
        return (byte)Integer.parseInt(str, 2);
    }

    /**
     * 获取下行命令中需要的日期类型的参数
     * @return
     */
    public static String[] getTime(String time,String sign){
        SimpleDateFormat sdf = new SimpleDateFormat("mm-HH-dd-MM-yy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmm");
        SimpleDateFormat sdf3 = new SimpleDateFormat("mm-HH-dd");
        String[] day = null;
        switch (sign){
            case "0302":
                Date parse;
                try {
                    parse = sdf2.parse(time);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                day = StringUtils.split(sdf3.format(parse), "-");
                break;
            case "0401":
                day = StringUtils.split(sdf.format(new Date()), "-");
                break;
        }
        return day;
    }


    /**
     * IP解析
     * @param ipHex
     * @return
     */
    public static String hexToIp(String ipHex) {
        StringBuilder ip = new StringBuilder();
        for (int i = 0; i < ipHex.length(); i += 2) {
            String part = ipHex.substring(i, i + 2);
            ip.append(Integer.parseInt(part, 16));
            if (i < ipHex.length() - 2) {
                ip.append(".");
            }
        }
        return ip.toString();
    }

    /**
     * 端口解析
     * @param portHex
     * @return
     */
    public static int hexToPort(String portHex) {
        return Integer.parseInt(portHex, 16);
    }

    /**
     * 解析表号
     * @param inputStr
     * @return
     */
    public static String convertCustomFormat(String inputStr) {
        if (inputStr.length() % 2 != 0) {
            throw new IllegalArgumentException("Input string length should be even.");
        }

        StringBuilder output = new StringBuilder();
        for (int i = inputStr.length(); i > 0; i -= 2) {
            output.append(inputStr.substring(i - 2, i));
        }

        return output.toString();
    }

    /**
     * 验证
     * @param bit
     * @return
     */
    public static boolean getCsForAllType(byte[] bit, int index, byte[] type)
    {
        boolean flag = true;
        if (bit != null & bit.length > 0)
        {

            if (flag)
            {
                if (bit.length <= 0)
                {
                    flag = false;
                }
                else if (bit[0] != (byte)0x68)
                {
                    flag = false;
                }
                else if (bit[(bit.length - 1)] !=  (byte)0x16)
                {
                    flag = false;
                }
                else
                {
                    byte[] temp1 = new byte[bit.length - 8];
                    System.arraycopy(bit, 6, temp1, 0, temp1.length);
                    byte temp = CharacterParsingCommon.getTotalForByte(temp1);
                    if (temp != bit[(bit.length - 2)])
                    {
                        flag = false;
                    }
                }
            }

        }

        return flag;
    }

    //解析压力域
    public static String getPressureVFromByte(byte[] bit)
    {
        String str = "";
        double d = 100;
        d = Double.parseDouble(Integer.toHexString(bit[0]& 0xFF)+200)/d;
        return d + "";
    }
    /**
     * 解析 阀控 状态
     * @param bit
     * @return
     */
    public static String getValveStatus(byte bit){
        String binaryString = String.format("%8s", Integer.toBinaryString(bit & 0xFF)).replace(' ', '0');

        String flag = "3";
        if(binaryString.substring(0,2).equals("00")){
            flag = "1";//开阀
        }else {
            flag = "0";//关阀
        }
        return flag;
    }

    /**
     *
     * @param bit
     * @param type 0：当前数据、1：日冻结数据，2：月冻结数据
     * @return
     */
    public static JSONObject getDSDateinfoFromByte(byte[] bit,int type,JSONObject json)
    {
        JSONObject jo = new JSONObject();
        try
        {
            if (bit.length > 8)
            {
                jo.put("type", 5);
                jo.put("type_msg", "集中器四联");//终端类型
                byte[] temp = new byte[5];
                System.arraycopy(bit, 7, temp, 0, temp.length);
                jo.put("add", getAddressFieldPacket(temp));//终端类型
                Integer index_num = 21;//163301112110 01 00000000 //水表状态00 00
                JSONArray json_temp = new JSONArray();
                temp = new byte[2];
                System.arraycopy(bit, 15, temp, 0, temp.length);
                jo.put("total", Integer.parseInt(CharacterParsingCommon.get16tobcd(temp,true)));
                System.arraycopy(bit, 17, temp, 0, temp.length);
                jo.put("xh", Integer.parseInt(CharacterParsingCommon.get16tobcd(temp,true)));
                try{
                    while (index_num < bit.length-2)
                    {
                        JSONObject item = new JSONObject();
                        try{

                            temp = new byte[6];
                            System.arraycopy(bit, index_num, temp, 0, temp.length);
                            String meterAddress = CharacterParsingCommon.get16tobcd(temp,true);
                            item.put("add", meterAddress);
                            //流量 只取一个因子,单位固定为立方米
                            temp = new byte[4];
                            System.arraycopy(bit, index_num + 8, temp, 0, temp.length);//根据解析后数据 猜8

                            item.put("TotalFlow", Integer.parseInt(CharacterParsingCommon.get16tobcd(temp,true)));
                            //阀控
                            temp = new byte[1];
                            System.arraycopy(bit, index_num + 11, temp, 0, temp.length);
                            item.put("valveStatus", getValveStatus(temp[0]));

                            //电池
                            temp = new byte[1];
                            System.arraycopy(bit, index_num + 12, temp, 0, temp.length);
                            item.put("voltage", getPressureVFromByte(temp));
                        }catch (Exception e){
                            System.out.println(e.getMessage());

                        }

                        index_num = index_num + 13 ;
                        json_temp.add(item);
                    }
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }

                jo.put("info", json_temp);
            }
        }
        catch (Exception e)
        {

        }
        json.put("code","1");
        json.put("msg","成功");
        return jo;
    }





    /**
     * 日冻结数据
     * @param concentratorAddress
     * @param meterAddress
     * day 240523
     * @return
     */
    public static byte[] getDayReading(String concentratorAddress,String meterAddress,String day){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        try {
            Date parse = sdf.parse(day);
            day = sdf2.format(parse);
            System.out.println(day);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        byte[] bit = new byte[11];
        byte[] temp = new byte[3];
        temp = CharacterParsingCommon.get16tobcd(day,false);
        System.arraycopy(temp, 0, bit, 0, temp.length);
        bit[3] = 0x10;
        temp = new byte[6];
        temp = new byte[]{(byte)0xFF,(byte)0xFF,0x00,0x00,(byte)0xFF,(byte)0xFF};
        temp = "".equals(meterAddress)? temp : CharacterParsingCommon.get16tobcd(meterAddress,false);
        System.arraycopy(temp, 0, bit, 4, temp.length);
        bit[10] = 0x45;
        return getpacketbody(concentratorAddress,7,0,bit,1);
    }

    /**
     *
     * @param address 集中器地址
     * @param afntype
     * @param fntype
     * @param body 其他
     * @return
     */
    public static byte[] getpacketbody(String address,int afntype,int fntype,byte[] body,int control){
        int num = 9;
        if (body != null) {
            num = 9 + body.length;
        }
        byte[] bit = new byte[8+num];
        bit[0] = 0x68;
        byte[] temp = new byte[2];//长度
        temp = getpacketLength(num);
//        temp = calculateLinkLayerLength(num);
        System.arraycopy(temp, 0, bit, 1, 2);
        System.arraycopy(temp, 0, bit, 3, 2);
        bit[5] = 0x68;
        bit[6] = getControlPacket(control);
        temp = new byte[5];//地址域
        temp = getAddressFieldPacket(address);
        System.arraycopy(temp, 0, bit, 7, 5);
        //AFN
        bit[12] = AFN[afntype];
        //seq
//        bit[13] = getSEQPacket(1,1,0);
        bit[13] = getSEQPacket(1,1,1);
        //fn
        bit[14] = Fn[afntype][fntype];
        if(body != null){
            System.arraycopy(body, 0, bit, 15, body.length);
        }
        //验证和
        temp = new byte[num];//地址域
        System.arraycopy(bit, 6, temp, 0, num);
        bit[bit.length-2] = CharacterParsingCommon.getTotalForByte(temp);
        bit[bit.length-1] = 0x16;
        System.out.println("发出的命令："+CharacterParsingCommon.convertString(bit));
        return bit;
    }

    /**
     * 生成端口命令
     * @param portDecimal 端口值 如8080
     * @return
     */
    public static byte[] getPort(int portDecimal){
        // 将端口号转换为十六进制字符串，高位在后
        String portHex = Integer.toHexString(portDecimal);

        // 确保端口号使用两个字节表示
        if (portHex.length() % 2 != 0) {
            portHex = "0" + portHex; // 补齐到偶数位
        }

        // 创建一个长度为2的字节数组来存储端口号的十六进制表示
        byte[] portBytes = new byte[2];

        // 将高位字节放在后面
        for (int i = 0; i < 2; i++) {
            String hexByte = portHex.substring(i * 2, i * 2 + 2); // 每次取两个字符（一个字节）
            portBytes[1 - i] = (byte) Integer.parseInt(hexByte, 16); // 高位在后，所以反向存储
        }
        return portBytes;
    }

}
